package test.com.sky.thread;

/**
 * 生产者和消费者问题;
 */
public class PC {
    private static Integer count = 0;
    private static final Integer Total = 20;
    private static final String flag = "agree";


    private class Producer implements Runnable {
        @Override
        public void run() {
            for (int i = 0;  ; i++) {

                synchronized (flag) {
                    while (count.equals(Total)) {
                        try {
                            flag.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    count++;
                    System.out.println("INFO  " + Thread.currentThread().getName() + "   生产者生产, 池中的数量是:" + count);
                    flag.notify();
                }

                try {
                    Thread.sleep(4000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private class Consumer implements Runnable {

        @Override
        public void run() {
            for (int i = 0;  ; i++) {

                synchronized (flag) {
                    while (count == 0) {
                        try {
                            flag.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    count--;
                    System.out.println("INFO  " + Thread.currentThread().getName() + "   消费者消费，池中的数量是:" + count);
                    flag.notify();
                }

                try {
                    Thread.sleep(8000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static void main(String[] args) {
        PC PC = new PC();
        new Thread(PC.new Producer(), "producer - 1").start();
        new Thread(PC.new Consumer(), "consumer - 1").start();
        new Thread(PC.new Producer(), "producer - 2").start();
        new Thread(PC.new Consumer(), "consumer - 2").start();

    }

}
